package com.bite.blog.controller;


import com.bite.blog.contant.Constants;
import com.bite.blog.model.Result;
import com.bite.blog.model.UserInfo;
import com.bite.blog.service.UserService;
import com.bite.blog.utils.JwtUtils;
import com.bite.blog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String username,String password){
        // 1. 参数校验
        if (!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            return Result.fail("账号或密码不能为空");
        }
        // 2. 校验密码是否正确
        // 从数据库查找用户
        UserInfo userInfo = userService.selectByName(username);
        if (userInfo==null){
            log.info("用户不存在");
            return Result.fail("用户不存在");
        }
        // 3. 密码错误,返回错误信息
        if(!SecurityUtils.verify(password,userInfo.getPassword())){
            log.info("密码错误");
            return Result.fail("密码错误");
        }
        // 4. 密码正确,返回token
        Map<String,Object> claim = new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token = JwtUtils.genJwtToken(claim);
        return Result.success(token);
    }

    /**
     * 获取当前登录用户的信息 -> 从token中获取
     * @return
     */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        // 获取token
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        // 从token中获取登录用户ID
        Integer userId = JwtUtils.getIdByToken(token);
        if (userId==null){
            // 用户未登录
            return null;
        }
        UserInfo userInfo = userService.selectById(userId);
        return userInfo;

    }
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        // 1.根据博客id,获取作者id
        // 2.根据作者id,获取作者信息
        if (blogId<=0) return null;
        UserInfo userInfo = userService.getAuthorInfo(blogId);
        return userInfo;
    }
}
